csv
模組可以輕鬆操作這種檔案格式。import csv
data = [
['Name', 'Age', 'City'],
['Alice', 23, 'New York'],
['Bob', 34, 'Los Angeles'],
['Charlie', 29, 'Chicago']
]
with open('people.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
import csv
with open('people.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
openpyxl
庫可以寫入和讀取 .xlsx
文件格式。from openpyxl import Workbook
wb = Workbook()
ws = wb.active
data = [
['Name', 'Age', 'City'],
['Alice', 23, 'New York'],
['Bob', 34, 'Los Angeles'],
['Charlie', 29, 'Chicago']
]
for row in data:
ws.append(row)
wb.save('people.xlsx')
from openpyxl import load_workbook
wb = load_workbook('people.xlsx')
ws = wb.active
for row in ws.iter_rows(values_only=True):
print(row)
mysql-connector
模組可以對 MySQL 資料庫進行操作。import mysql.connector
# 連接 MySQL
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="testdb"
)
cursor = conn.cursor()
# 創建資料表
cursor.execute("CREATE TABLE IF NOT EXISTS people (name VARCHAR(255), age INT, city VARCHAR(255))")
# 插入數據
sql = "INSERT INTO people (name, age, city) VALUES (%s, %s, %s)"
val = [("Alice", 23, "New York"), ("Bob", 34, "Los Angeles"), ("Charlie", 29, "Chicago")]
cursor.executemany(sql, val)
# 提交變更
conn.commit()
print(cursor.rowcount, "筆記錄已插入。")
# 查詢資料
cursor.execute("SELECT * FROM people")
result = cursor.fetchall()
for row in result:
print(row)
# 關閉連接
conn.close()
cursor.execute("SELECT * FROM people")
rows = cursor.fetchall()
for row in rows:
print(row)
sqlite3
模組,我們可以對 SQLite 資料庫進行操作。import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS people
(name TEXT, age INTEGER, city TEXT)''')
cursor.execute("INSERT INTO people (name, age, city) VALUES ('Alice', 23, 'New York')")
cursor.execute("INSERT INTO people (name, age, city) VALUES ('Bob', 34, 'Los Angeles')")
cursor.execute("INSERT INTO people (name, age, city) VALUES ('Charlie', 29, 'Chicago')")
conn.commit()
conn.close()
gspread
和 Google Sheets API 操作試算表。首先,你需要在 Google Cloud 註冊並啟用 Google Sheets API,並下載憑證 JSON 文件。
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# 設定 API 範圍
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
# 加載憑證
creds = ServiceAccountCredentials.from_json_keyfile_name('your_credentials.json', scope)
client = gspread.authorize(creds)
# 開啟 Google 試算表
sheet = client.open('Test Spreadsheet').sheet1
# 寫入數據到 Google 試算表
data = ["Alice", 23, "New York"]
sheet.append_row(data)
# 讀取數據
records = sheet.get_all_records()
for record in records:
print(record)
透過本次學習,我們探索了從簡單的 CSV 文件到 Google 試算表的數據操作過程,並熟悉了 MySQL 和 SQLite 這兩種流行的資料庫系統。無論是本地數據處理還是雲端資料管理,這些工具都能大大提高我們的工作效率。